package com.javaweb.blogcite.controller;


import com.javaweb.blogcite.DTO.LoginRequest;
import com.javaweb.blogcite.DTO.LoginResponse;
import com.javaweb.blogcite.aspect.JwtAspect;
import com.javaweb.blogcite.aspect.JwtCheck;
import com.javaweb.blogcite.common.ResponseResult;
import com.javaweb.blogcite.pojo.Admin;
import com.javaweb.blogcite.service.LoginService;
import com.javaweb.blogcite.util.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class LoginController {

    @Resource
    private LoginService loginService;

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAspect.class);

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Value("${jwt.secret}")
    private String secretKey;

    @PostMapping("/api/admin/login")
    public ResponseResult<LoginResponse> login(@RequestBody LoginRequest loginRequest, HttpServletRequest request, HttpServletResponse response){
        ResponseResult<LoginResponse> result = new ResponseResult<>();

        String code = request.getSession().getAttribute("captchaText").toString();
        if (code.equals(loginRequest.getCaptcha())){
            LoginResponse login = loginService.login(loginRequest, response, loginRequest.getRemember());
            if(login != null){
                result.setCode(0);
                result.setMsg("");
                result.setData(login);
            }else {
                result.setCode(500);
                result.setMsg("用户名或密码错误");
            }
            return result;
        }
        // 验证码错误
        result.setCode(500);
        result.setMsg("验证码错误");
        return result;
    }

    @JwtCheck
    @GetMapping("/api/admin/whoami")
    public ResponseResult<LoginResponse> whoami(@RequestHeader(value = "Authorization") String authHeader) {
        ResponseResult<LoginResponse> result = new ResponseResult<>();
        String id = null;
        if (authHeader!= null && authHeader.startsWith(tokenHead)) {
            String authToken = authHeader.substring(tokenHead.length());
            id = JwtTokenUtil.getUserNameFromToken(authToken);
        }

        LoginResponse loginResponse = loginService.whoami(id);

        result.setCode(0);
        result.setMsg("");
        result.setData(loginResponse);
        return result;
    }
}
